//
//  DnpLocation.m
//  dnp_plugin
//
//

#import "DnpLocation.h"

@implementation DnpLocation{
    CLLocationManager *_geoLocationManager;
}

+ (instancetype)sharedInstance {
    static DnpLocation *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _geoLocationManager = [[CLLocationManager alloc] init];
        [_geoLocationManager requestWhenInUseAuthorization];
        _geoLocationManager.desiredAccuracy = kCLLocationAccuracyBest;
        _geoLocationManager.distanceFilter = 0;
        _geoLocationManager.delegate = self;
    }
    return self;
}

- (void)beginUpdates {    
    [self endUpdates];
    [_geoLocationManager startUpdatingLocation];
}

- (void)endUpdates {
    [_geoLocationManager stopUpdatingLocation];
}

#pragma mark - CLLocationManagerDelegate

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    [manager startUpdatingLocation];
    
    CLLocation *location = [locations lastObject];
    if (!location) return;
    
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> *placemarks, NSError *error) {
        if (error) {
            return;
        }
        
        CLPlacemark *placemark = [placemarks firstObject];        
        
        NSString *pulling = placemark.country ?: @"";
        NSString *burdock = placemark.administrativeArea ?: @"";
        NSString *jacket = placemark.locality ?: @"";
        NSString *pipeclay = placemark.subLocality ?: @"";
        NSString *idea = placemark.thoroughfare ?: @"";
        NSString *huge = placemark.ISOcountryCode ?: @"";
        NSString *openly = location.coordinate.latitude == 0 ? @"0" : [NSString stringWithFormat:@"%.6f", location.coordinate.latitude];
        NSString *carrying = location.coordinate.longitude == 0 ? @"0" : [NSString stringWithFormat:@"%.6f", location.coordinate.longitude];
        
        NSDictionary *locationMap = @{
            @"pulling": pulling,
            @"burdock": burdock,
            @"jacket": jacket,
            @"pipeclay": pipeclay,
            @"idea": idea,
            @"huge": huge,
            @"openly": openly,
            @"carrying": carrying,
        };
        
        if (self.locationHander) {
            self.locationHander(locationMap);
        }
        
        [manager stopUpdatingLocation];
    }];
}


@end
